import numpy as np
import pandas as pd
import networkx as nx

# 知识点名称列表
nodes = [
    "选择1", "选择2", "选择3", "选择4", "选择5", "选择6", "选择7", "选择8", "选择9", "选择10",
    "填空1", "填空2", "填空3", "填空4", "填空5", "填空6",
    "计算1", "计算2", "证明1", "证明2", "综合应用1", "综合应用2"
]

# 读取没有表头和索引的邻接矩阵
df = pd.read_excel('试卷知识点关联规则汇总.xls', header=None)
df.index = nodes
df.columns = nodes
matrix = df.values

# 构建有向图
g = nx.DiGraph()
g.add_nodes_from(nodes)
for i, row in enumerate(matrix):
    for j, val in enumerate(row):
        if val == 1:
            g.add_edge(nodes[i], nodes[j])

# 检测所有环路
cycles = list(nx.simple_cycles(g))

# 输出到txt文件
with open('cycles.txt', 'w', encoding='utf-8') as f:
    if cycles:
        f.write("检测到的环路如下：\n")
        for cycle in cycles:
            f.write(" -> ".join(cycle) + "\n")
    else:
        f.write("未检测到环路，图为有向无环图（DAG）。\n")
